import fa from "element-ui/src/locale/lang/fa";

var allFieldMap = new Map();
var associatedFieldsList = []; // 关联字段列表，这些字段将在参数处理完成后，进行再加工
var localCallback = null;

// 0.1 获取参数key,参数key用于唯一的确定一个参数
export function getParamKey(param){
    var paramId = param.id;
    var groupId = param.groupId;
    var orders  = param.userSelection.orders
    var key = groupId + "_" + paramId + "_" + orders;
    return key;
}
// 0.2 自定义生成key
export function makeParamKey(groupId,paramId,orders){
    var key = groupId + "_" + paramId + "_" + orders;
    return key;
}

// 0.3 页面字段 - 处理关联字段
export function processingAssociatedFields(cusParam,allFieldList){

    if(cusParam.attr3 == undefined || cusParam.attr3.length <= 0){
        return
    }

    var attr3 = JSON.parse(cusParam.attr3);
    if(attr3.condition == "show"){
        let dKey = makeParamKey(cusParam.groupId,attr3.id,cusParam.userSelection.orders);
        let dParam = findParamByKey(dKey,allFieldList);
        if(dParam == null){
            console.log("未找到参数key为"+ dKey +"的关联字段");
            return;
        }

        if(cusParam.id == '10000'){ // 附件关联字段处理

            if(cusParam.userSelection.parameterValue.length > 0){
                dParam.isShow = true;
            }else{
                dParam.isShow = false;
            }

        }else if(cusParam.id == "10200-013"){  // 金课排名关联字段处理
            if(cusParam.userSelection.parameterValue == '否'){
               dParam.isShow = false;
            }else{
               dParam.isShow = true;
            }
        }

    }
}

// 0.4 通过key从 allFieldList 中查询参数
export function findParamByKey(key,paramList){

   var keyArray = key.split("_");
   var paramId = keyArray[1];

   for(var pIndex=0;pIndex<paramList.length;pIndex++){
         if(paramList[pIndex].id === paramId){
            return paramList[pIndex];
         }
   }
   return null;
}

// 0.41 通过key从 allFieldList 中查询参数
export function findGroupById(groupId,allFieldList){

    for(var mIndex=0;mIndex<allFieldList.length;mIndex++){
        var module = allFieldList[mIndex];
        for(var gIndex=0;gIndex<module.groupList.length;gIndex++){

            var group = module.groupList[gIndex];
            if(group.id === groupId){

               return group.section;

            }else{

               // 寻找二级组
               for(let sIndex=0;sIndex<group.section.length;sIndex++){
                  let paramList = group.section[sIndex];

                  for(let pIndex=0;pIndex<paramList.length;pIndex++){
                     if(paramList[pIndex].baseParameterGroupParamList.length>0 &&  groupId === paramList[pIndex].baseParameterGroupParamList[0][0].groupId){
                        return paramList[pIndex].baseParameterGroupParamList;
                     }
                  }
               }

            }

        }
    }
    return null;
}

// 0.5 判断必填的关联字段
function attachmentDesAirspace(allFieldList){

    for(var i=0;i<allFieldList.length;i++){
        var paramList = allFieldList[i];
        for(var pIndex=0;pIndex<paramList.length;pIndex++){

            let param = paramList[pIndex];
            if(param.attr3 !== undefined && param.attr3.length > 0){

                let pparam = attachmentDesAirspace_1(param,paramList);
                if(pparam != undefined){
                    return "请填写：\"" + pparam.name + "\"";
                }
            }
        }
    }
}
// 0.51 判断必填的关联字段 - 验证操作
function attachmentDesAirspace_1(param,allFieldList) {

    let groupId = param.groupId;

    if(param.userSelection.parameterValue.length > 0 && param.attr3 !== undefined && JSON.parse(param.attr3).required === "required"){

        let paramId = JSON.parse(param.attr3).id;
        if(paramId !== undefined){
            let key = makeParamKey(groupId,paramId,param.userSelection.orders);
            let p = findParamByKey(key,allFieldList);
            // 必须确保关联字段已显示，因为被关联的字段并不是根据是否有值来控制关联字段的显示、隐藏的
            if(p.isShow === true && p.userSelection.parameterValue.length <= 0){
                return p;
            }
        }

    }
}

// 0.6 正则验证参数值格式
function regularJudgmentParamList(allFieldList){

   for(let i=0;i<allFieldList.length;i++){

      let paramList = allFieldList[i];
      for(var pIndex=0;pIndex<paramList.length;pIndex++){
         let param = paramList[pIndex];

         // 不验证隐藏字段
         if(param.isShow !== true){
            continue;
         }

         // 必填验证
         if(param.attr2 === "1"){
            if(param.type.indexOf("range") !== -1){  // 日期范围
               if((param.userSelection.startDate == null || param.userSelection.startDate == "") &&
               (param.userSelection.endDate == null || param.userSelection.endDate == "") &&
               (param.userSelection.parameterValue == null || param.userSelection.parameterValue == "")){
                  return "请填写 \"" + param.name + "\"";
               }
            }else{
               if(param.userSelection.parameterValue == null || param.userSelection.parameterValue == ""){

                  if(param.id === "10100-031"){ // 照片
                     return "请上传 \"" + param.name + "\"";
                  }else{
                     return "请填写 \"" + param.name + "\"";
                  }

               }
            }
         }

         // 特殊字段必填验证
         let result = specialFieldsMustBeVerified(param,paramList);
         if(result !== undefined){
            return result;
         }

         // 规则验证
         result = ruleValidationParam(param);
         if(result !== undefined){
            return result;
         }

         // 正则验证
         result = regularJudgmentParam(param);
         if(result !== undefined){
            return result;
         }
      }
   }

}
// 0.61 正则验证一个参数
export function regularJudgmentParam(param){
   if(param === undefined){
      return undefined;
   }

   if(param.isShow === false){
      return undefined;
   }

   if(param.attr5 === undefined){
      return undefined;
   }

   // 参数值为空时不验证正则，但不包括日期区间参数
   if(param.type.indexOf("range") === -1 && param.userSelection.parameterValue === ""){
      return undefined;
   }


   let json   = parsingAttr5(param);
   let type   = json.type;
   let regexp = json.data;
   let msg    = json.msg;

   // 将所有'\'替换为'\\'，以确保JSON通够正常解析
   switch(type){   // 1:日期，2：正则，3：照片，4：数字，5.排序
      case "1":{

         let dateRange = regexp.split("-");
         let start = 0;
         if(dateRange[0] !==""){
            start = Date.parse(dateRange[0]);
         }
         // let end = new Date().getTime();
         let end = Number.MAX_SAFE_INTEGER;
         if(dateRange[1] !== ""){
            end = Date.parse(dateRange[1]);
         }

         if(param.type.indexOf("range") !== -1){ // 日期区间

            let startDate = Date.parse(param.userSelection.startDate);
            let endDate = Date.parse(param.userSelection.endDate);
            if(isNaN(startDate) === true){
               let errorMsg = "";
               if(param.userSelection.startDate == "" || param.userSelection.startDate == null){
                  errorMsg =  param.name + " 填写有误，请输入起始时间 !";
               }else{
                  errorMsg = param.name + " 格式有误，请您重新选择一下起始时间 !";
               }
               return errorMsg;
            }
            if(isNaN(endDate) === true){
               // endDate = new Date().getTime()
               let errorMsg = "";
               if(param.userSelection.endDate == "" || param.userSelection.endDate == null){
                  errorMsg =  param.name + " 填写有误，请输入结束时间 !";
               }else{
                  errorMsg = param.name + " 格式有误，请您重新选择一下结束时间 !";
               }
               return errorMsg;
            }

            if(startDate > endDate){
               let errorMsg =  param.name + " 填写有误，起始时间不能大于结束时间 !";
               return errorMsg;
            }

            if(startDate < start || startDate > end ){
               let errorMsg =  param.name + " 填写有误，"+ msg +" !";
               return errorMsg;
            }else if(endDate < start || endDate >end ){
               let errorMsg =  param.name + " 填写有误，"+ msg +" !";
               return errorMsg;
            }

         }else{ // 普通单个日期

            let value = Date.parse(param.userSelection.parameterValue);
            if(isNaN(value) === true){
               let errorMsg =  "";
               if(value == "" || value == null){
                  errorMsg =  "请输入 " + param.name + " !";
               }else{
                  errorMsg = param.name + " 格式有误，请您重新选择一下 !";
               }
               return errorMsg;
            }
            if(value < start || value >end ){
               let errorMsg =  param.name + " 填写有误，"+ msg +" !";
               return errorMsg;
            }
         }
         break;
      }
      case "2":{

         if(!new RegExp(regexp,'i').test(param.userSelection.parameterValue)){
            let errorMsg = param.name + " 填写有误，"+ msg +" ！";
            return errorMsg;
         }
         break;
      }
      case "3":{

         break;
      }
      case "4":{

         let dataArray = json.data.split("-");
         let start = parseFloat(dataArray[0]);
         let end = parseFloat(dataArray[1]);
         let value = parseFloat(param.userSelection.parameterValue);
         if(isNaN(value)){
            return param.name + " 输入有误，请输入正确的数字 ！";
         }
         if(value < start || value > end){
            return param.name + " 输入有误，"+ msg +" ！";
         }
         break;
      }
      case "5":{

         let errorMsg = param.name + " 输入有误，" + "请按照格式 “本人排序/总人数” 填写，例如：5/40";
         if(param.userSelection.parameterValue.indexOf("/") === -1){
            return errorMsg;
         }

         let array = param.userSelection.parameterValue.split("/");
         if(array.length !== 2){
            return errorMsg;
         }

         let valueA = parseInt(array[0]);
         let valueB = parseInt(array[1]);
         if(isNaN(valueA) || isNaN(valueB)){
            return errorMsg;
         }

         let dataArray = json.data.split("-");
         let start = parseInt(dataArray[0]);
         let end = parseInt(dataArray[1]);
         if(valueA < start || valueB > end){
            return param.name + " 输入有误，" + msg;
         }
         break;
      }

   }
}

// 0.7 参数规则验证
function ruleValidationParam(param){

   if(param.attr2 === "0" && param.userSelection.parameterValue === ""){
      return undefined;
   }

   // 数字验证
   if(param.typeValidate === "number" && param.userSelection.parameterValue === ""){
      let msg = param.name + " 填写有误，请输入正确的数字 !";
      return msg;
   }

   // 整数验证
   if(param.typeValidate === "integer"  && (param.userSelection.parameterValue === "" || param.userSelection.parameterValue.indexOf(".") !== -1)){

      let msg = "";
      if(param.userSelection.parameterValue.indexOf(".") !== -1){
         msg = param.name + " 填写有误，请输入正整数 !";
      }else{
         msg = param.name + " 填写有误，请输入正确的数字 !";
      }
      return msg;
   }

}

// 0.8 解析attr5
function parsingAttr5(param){

   if(param.attr5 === undefined){
      return undefined;
   }

   // JSON不能解析含有正则的字符串，因为正则中各种特殊字符串会导致解析失败;
   // 因此，此处通过手动截取字符串的方式找到json的中的数据

   // type
   let typeKey = "type\":\"";
   // 正则
   let dateKey = "data\":\"";
   // msg
   let msgKey = "msg\":\"";

   // 取出type
   let startIndex =  param.attr5.indexOf(typeKey) + typeKey.length;
   let endIndex = startIndex + 1;
   let type = param.attr5.substring(startIndex,endIndex);

   // 取出正则
   startIndex =  param.attr5.indexOf(dateKey) + dateKey.length;
   endIndex   =  param.attr5.indexOf(msgKey) - 3;
   let regexp = param.attr5.substring(startIndex,endIndex);

   // 取出msg
   startIndex =  param.attr5.indexOf(msgKey) + msgKey.length;
   endIndex   =  param.attr5.length - 2;
   let msg = param.attr5.substring(startIndex,endIndex);

   return {
      type:type,
      data:regexp,
      msg:msg
   };
}

// 0.9.0 特殊字段必填验证：一对多关联字段处理
//       二级表指导研究生情况中“是否被评优/被抽查”为“是”时，其它字段为必填
function specialFieldsMustBeVerified(param,paramList){

   // 确认字段为"是否被评优/被抽查"
   if(param.id === "5-10500-006-003"){
      if(param.userSelection.parameterValue == "是"){

         for(var pIndex=0;pIndex<paramList.length;pIndex++){

            let localParam = paramList[pIndex];
            if(localParam.id === "10000" || localParam.id === "10001"){
               continue;
            }else{
               if(determineParameterIsEmpty(localParam)){
                  return "请填写 " + localParam.name;
               }
            }
        }

      }
   }

}

// 0.10.0 判断参数值是否为空,为空时返回true
function determineParameterIsEmpty(param){

   var baseInfo_value = param.userSelection.parameterValue;
   if(baseInfo_value === null || baseInfo_value === undefined || baseInfo_value.toString().trim().length <= 0){

      if((param.userSelection.startDate === null || param.userSelection.startDate === undefined || param.userSelection.startDate.trim().length <= 0) &&
         (param.userSelection.endDate === null || param.userSelection.endDate === undefined || param.userSelection.endDate.length <= 0)){
         return true;
      }
   }
   return false;
}






// 1.0 处理group
export function processingGroupData(groupData){

    // 处理userSelection，填充为空的值
    processingUserSection(groupData);

    // 获取组中的数据组数
    var selectionLength = groupData[0].userSelection.length;
    if(selectionLength <= 0){
        selectionLength = 1;
    }

    var groupSection = [];
    for(var sIndex=0;sIndex<selectionLength;sIndex++){
        // 处理参数
        var paramList = processingParameters(JSON.parse(JSON.stringify(groupData)),sIndex);

        let pList = JSON.parse(JSON.stringify(paramList));
        groupSection.push(pList);

        for(let i=0;i<associatedFieldsList.length;i++){
            processingAssociatedFields(associatedFieldsList[i],pList);
         }
    }

   return {
      "allFieldList":groupSection, // 所有数据字段
      "allFieldMap":allFieldMap    // 所有原始字段，用于对比字段值是否被保存
   }
}

// 1.2 处理seciton中每个参数列表
export function processingParameters(paramlist,sectionIndex){
    // group 组
    // sectionIndex 组的第几份参数(索引)

    var defaultOrders = sectionIndex;
    if(paramlist.length > 0 && paramlist[0].userSelection.length > 0){
        if(paramlist[0].userSelection.length > 0){
            defaultOrders = paramlist[0].userSelection[sectionIndex].orders;
        }
    }

    for(var e=0;e<paramlist.length;e++){
        var param = paramlist[e];

        if(param.id == '12000-001'){
            param;
        }

        // 处理每个字段
        var userSelection = {
            orders:defaultOrders,
            parameterValue:""
        };
        if(param.userSelection.length > 0 && sectionIndex < param.userSelection.length){
            if(param.userSelection[sectionIndex] != null){
                userSelection = param.userSelection[sectionIndex];
            }
        }

        param.userSelection = userSelection;
        param.isShow = true;

        // console.log(param);
        if(param.userSelection.parameterValue == undefined){
            param.userSelection.parameterValue = "";
        }

        // 通过参数类型处理参数值
        processingParamValueByType(param);

        param.placeholder = "请输入内容"; // 默认placeholder
        param.isDisable   = false;

        // 0.1 特殊处理字段：指导的硕士生或博士数量字段
        if(param.id == "10500-005"){
            // param.type = "text_10500_005";
            if(parseInt(param.userSelection.parameterValue) == 0){
                // param.isDisabledBaseParameterGroup = true;
            }
        }

        // 0.2 特殊处理字段：设置样式
        if(param.groupId == "10500" || param.groupId == "12500" || param.groupId == "12300"){
            param.class = "formItem_0_5";
        }else{
            param.class = "";
        }

        // 0.3 特殊处理字段：本人排序
        if(param.id == "10900-003"){
            param.placeholder = "序号/总人数";
            param.regular = "^\\d+\\/\\d+$";    // 参数值验证正则
            param.valueExamples = "2/10";       // 参数值示例
        }

        // 0.4 特殊处理字段：更新“现职称所属岗位”options列表
        if(param.id == "10100-018"){
            if(localCallback != null){
                localCallback(param);
            }
        }

        // 0.5 特殊处理字段：基本信息-奖惩情况 设置默认值为0
        if(param.id == "10100-030"){
            if(param.userSelection.parameterValue === ""){
                param.userSelection.parameterValue = "0";
            }
        }

        // 0.6 特殊处理字段：设置字段禁用状态
        if(param.attr3 != undefined && param.attr3 !== "" && JSON.parse(param.attr3).condition == "disable"){
            param.isDisable = true;
        }

        // 0.6.1 特殊处理字段：设置字段禁用状态
        if(param.isLevel === "2"){
            param.isDisable = true;
        }

        // 0.7 禁用字段的特殊处理
        if(param.isDisable && (param.typeValidate == "number" || param.typeValidate == "integer" ) && param.userSelection.parameterValue.trim().length <= 0){
            // 数字类型的二级表字段，默认值设为0
            param.userSelection.parameterValue = "0";
        }

        // 具有关联字段的参数
        if(param.attr3 != undefined && param.attr3.length > 0){
            associatedFieldsList.push(param);
        }

        allFieldMap.set(getParamKey(param),param.userSelection.parameterValue);
    }
    return paramlist;
}

// 1.3 通过参数类型处理参数值
export function processingParamValueByType(param){

   if(param.type == "date"){

      let json = parsingAttr5(param);
      if(json !== undefined){
         param.dateRange = json.data; // 设置可选择的时间范围

         let dateArray = json.data.split("-");
         if(dateArray.length > 0){
            param.defaultDate = dateArray[1]; // 设置可选择的时间范围
         }
      }

      if(param.typeValidate == "yyyy"){
          param.type = "date_year";
      }else if(param.typeValidate == "yyyy.MM"){
         param.type = "date_month";
      }else if(param.typeValidate == "yyyy.MM.dd"){
          param.type = "date_day";
      }else if(param.typeValidate.indexOf("yyyy.MM-yyyy.MM") != -1){
          param.type = "date_month_range";

          if(param.userSelection.parameterValue == "-至今"){
              param.userSelection.parameterValue = "";
          }

          let dArray = param.userSelection.parameterValue.split("-");
          param.userSelection.startDate = dArray[0];
          param.userSelection.endDate = dArray.length > 1?dArray[1]:"";

      }else if(param.typeValidate.indexOf("yyyy.MM.dd-yyyy.MM.dd") != -1){
          param.type = "date_day_range";

          if(param.userSelection.parameterValue == "-至今"){
              param.userSelection.parameterValue = "";
          }

          let dArray = param.userSelection.parameterValue.split("-");
          param.userSelection.startDate = dArray[0];
          param.userSelection.endDate = dArray.length > 1?dArray[1]:"";
      }
  }
}

// 1.4 处理userSection
export function processingUserSection(parameters){

    var ordersList = parameters[0].orderList;

    // 填充空userSection
    for(var pIndex=0;pIndex < parameters.length; pIndex++){
        var userSelectionList_1 = parameters[pIndex].userSelection;

        // 新的usersSelectiong列表值
        let newUserSelectionList = new Array();

        // 遍历所有真实存在的orders
        for(var oIndex = 0;oIndex < ordersList.length;oIndex++){
            // 当前orders
            let currentOrders = ordersList[oIndex];

            // 当前userSelection列表元素值的orders
            let uOrders = -1;
            let uObj = {};

            // 寻找与当前orders相同的userSelection元素
            for(var usIndex=0;usIndex < userSelectionList_1.length; usIndex++){
                uObj = userSelectionList_1[usIndex];
                uOrders = uObj.orders;
                if(parseInt(uOrders) === parseInt(currentOrders)){
                    break;
                }
            }

            // 若uOrders等于-1，或在userSelection列表中未找到当前orders的元素值时，则插入空值
            if(uOrders !== -1 && uOrders === currentOrders){
                // 已在userSelection中找到对应orders的值，则直接插入
                newUserSelectionList.push(JSON.parse(JSON.stringify(uObj)));
            }else{
                // 当前orders位置没有值时，插入空值
                newUserSelectionList.push({orders:currentOrders,parameterValue:""});
            }
        }
        parameters[pIndex].userSelection = JSON.parse(JSON.stringify(newUserSelectionList));

    }
}

// 1.5 处理参数值变化
export function processingParamValueChange(event,param,type1,paramList,that){

   var paramId = param.id;
   var key = getParamKey(param);

   // 日期控件的值可能为null
   event = event==null?"":event;

   if("10100-027" == paramId){
   // 0.2> 职称评审 - 现职称所属领域

      for(var i=0;i<paramList.length;i++){
         if("10100-027" == paramList[i].id){

            // 职称评审 - 现职称所属类型
            for(var pindex = 0;pindex < paramList[i].options.length;pindex++){
                  if(paramList[i].options[pindex].name == paramList[i].userSelection.parameterValue){
                     paramList[i+1].userSelection.parameterValue = "";
                     paramList[i+2].userSelection.parameterValue = "";
                     paramList[i+1].options = paramList[i].options[pindex].childList;
                     break;
                  }
            }
            break;
         }
      }

   }

   if(event instanceof Event && event.target.files instanceof FileList){
         if(event.target.files.length <= 0){
            // this.uploadAttachment();
         }else{

            if(param.type == "img"){ // 上传图片
               uploadImage(param,event,paramList,that);
            }else if(param.type == "file"){ // 上传文件
               uploadAttachment(param,event,paramList,that);
            }
         }
   }

   var value = that.paramValueMap.get(key)
   // 额外的类型判断
   var dateValueArray = value.split("-");
   if(type1 == "date_range_start"){
         value = dateValueArray[0];
   }else if(type1 == "date_range_end"){
         value = dateValueArray.length>1?dateValueArray[1]:"";
   }

   if(type1 == "date_range_start" || type1 == "date_range_end"){
         if(param.userSelection.startDate == null || param.userSelection.startDate == ""){
            param.userSelection.parameterValue = "";
         }else if(param.userSelection.endDate == null || param.userSelection.endDate == ""){
            param.userSelection.parameterValue = param.userSelection.startDate + "-至今";
         }else{
            param.userSelection.parameterValue = param.userSelection.startDate + "-" + param.userSelection.endDate;
         }
   }

   if(value == event){ // 参数值未发生变化时
      that.unsavedParamIdList.remove(key);
   }else{ // 参数值已变更时
      if(that.unsavedParamIdList.indexOf(key) == -1){
         that.unsavedParamIdList.push(key);
      }
   }

   // 处理关联字段
   processingAssociatedFields(param,paramList);
}

// 2.0 上传附件
function uploadAttachment(param,event,paramList,that){

   var size = event.target.files[0].size/1024/1024;
   if(size > 100){
      that.$message({message: '附件大小不能超过100M',type: 'error'});
      return;
   }

   that.$refs.fileUploadLoading.style.display = 'flex';

   var formData = new FormData;
   formData.append("multipartFiles",event.target.files[0]);
   formData.append("groupId",param.groupId);
   formData.append("parameterId",param.id);
   formData.append("orders",param.userSelection.orders);

   that.$api.infoEntryUploadFilePost(formData).then(res => {
      if(res.code == 200){
         let p = res.data[0];
         let key = makeParamKey(p.groupId,p.parameterId,p.orders);
         let resParam = findParamByKey(key,paramList);
         resParam.userSelection.parameterValue = p.url;

         // 处理关联字段
         processingAssociatedFields(resParam,paramList);
      }
   }).finally(function () {
      event.target.value = "";
      that.$refs.fileUploadLoading.style.display = 'none';
   });
}

// 2.1 上传图片
export function uploadImage(param,event,paramList,that){

   var size = event.target.files[0].size/1024/1024;
   if(size > 10){
      that.$message({message: '图片大小不能超过10M',type: 'error'});
         return;
   }

   that.$refs.fileUploadLoading.style.display = 'flex';
   // param.userSelection.parameterValue = "正在上传...";

   var oParam = param;
   var formData = new FormData;
   formData.append("multipartFiles",event.target.files[0]);
   that.$api.infoEntryUploadImagePost(formData).then(res => {
         if(res.code == 200){
            let resParam = findParamByKey(getParamKey(oParam),paramList);
            resParam.userSelection.parameterValue = res.message;
         }
   }).finally(function () {
         event.target.value = "";
         that.$refs.fileUploadLoading.style.display = 'none';
   });
}

// 2.2 导出数据
export function exportData(groupId,groupName,that){

   that.$api.infoEntryEnteredExportModelGet({
         method: 'get',
         url: '/admin/baseParameterGroup/exportModel?groupId=' + groupId,
         responseType: 'blob', // important
         // headers: { "Content-Type": "multipart/form-data" }
   }).then(res => {
         const url = window.URL.createObjectURL(new Blob([res]));
         const link = document.createElement('a');
         link.href = url;

         link.setAttribute('download',groupName + '.xlsx');

         document.body.appendChild(link);
         link.click();
   });
}

// 2.3 导出模板
export function exportModel(groupId,groupName,that){

   that.$api.infoEntryEnteredExportModelGet({
         method: 'get',
         url: '/admin/baseParameterGroup/exportModel1?groupId=' + groupId,
         responseType: 'blob', // important
         // headers: { "Content-Type": "multipart/form-data" }
   }).then(res => {
         const url = window.URL.createObjectURL(new Blob([res]));
         const link = document.createElement('a');
         link.href = url;

         link.setAttribute('download',groupName + '.xlsx');
         document.body.appendChild(link);
         link.click();
   });
}


// 3.0 保存
export function save(allFieldList,groupId,that,callback){

   // 0.1> 判断必填的关联字段
   var msg = attachmentDesAirspace(allFieldList);
   if(msg !== undefined){
       that.$message({message:msg,type: 'error'});
       callback(false);
       return
   }

   // 0.2> 正则验证所有参数格式
   msg = regularJudgmentParamList(allFieldList);
   if(msg != undefined){
      that.$message({message:msg,type: 'error'});
      callback(false);
      return
   }


   // 1.0> 将字段转为可提交的参数
   var dataList = JSON.parse(JSON.stringify(allFieldList));
   var valueList = [];
   conversionSectionToParam(valueList,dataList);


   var formData = new FormData;
   formData.append("list",JSON.stringify(valueList));
   formData.append("groupId",groupId);
   that.$api.infoEntryEnteredSavePost(formData).then(res => {
       if(res.code == 200){
         that.$message({message: '保存成功',type: 'success'});
         callback(true,res);
       }else{
         callback(false,res);
       }

   }).finally(()=>{
      // 不要重复调用回调
      // callback(false);
   });
}

// 3.1 保存 - 将section数组转为能够提交的参数
function conversionSectionToParam(valueList,sectionList){
   // 遍历所有section
   for(var sIndex=0;sIndex<sectionList.length;sIndex++){

       var paramList = sectionList[sIndex];

       for(var pIndex=0;pIndex<paramList.length;pIndex++){

            if(paramList[pIndex].type == "date_month_range" || paramList[pIndex].type == "date_day_range"){
                  var startDate = paramList[pIndex].userSelection.startDate;
                  if(startDate instanceof Date){
                     startDate = startDate.format("yyyy-MM-dd");
                  }
                  var endDate = paramList[pIndex].userSelection.endDate;
                  if(endDate instanceof Date){
                     endDate = endDate.format("yyyy-MM-dd");
                  }
                  paramList[pIndex].userSelection.parameterValue = startDate + "|" + endDate;

            }else if(paramList[pIndex].type.indexOf("date") != -1){

                  var dateValue = paramList[pIndex].userSelection.parameterValue;
                  if(dateValue instanceof Date){
                     dateValue = dateValue.format("yyyy-MM-dd");
                     paramList[pIndex].userSelection.parameterValue = dateValue;
                  }
            }

            if(paramList[pIndex].userSelection.parameterValue === null){
               paramList[pIndex].userSelection.parameterValue = "";
            }

            // 小数保留两位
            if(paramList[pIndex].typeValidate === "number" && paramList[pIndex].userSelection.parameterValue.indexOf(".")){
               paramList[pIndex].userSelection.parameterValue = parseFloat(paramList[pIndex].userSelection.parameterValue).toFixed(2);
            }

            valueList.push({
                  "id":paramList[pIndex].id,
                  "orders":paramList[pIndex].userSelection.orders,
                  "parameterGroupId":paramList[pIndex].groupId,
                  "parameterId":paramList[pIndex].id,
                  "parameterValue":paramList[pIndex].userSelection.parameterValue
            });
       }
   }
   return valueList;
}

// 3.2 删除section
export function deleteSection(paramList,that,callback){

   // 将字段转为可提交的参数
   var dataList = JSON.parse(JSON.stringify(paramList));
   var valueList = [];
   conversionSectionToParam(valueList,[dataList]);

   var formData = new FormData;
   formData.append("list",JSON.stringify(valueList));
   that.$api.deleteRecordAndItemPost(formData).then(res => {
       if(res.code == 200){
         that.$message({message: '删除成功',type: 'success'});
         callback(true,res);
       }else{
         callback(false,res);
       }

   }).finally(()=>{
      // 不要重复调用回调
      // callback(false);
   });

}
export function handleGetTimeData(that,type,callback){
    that.$api.getTimeData().then(res => {
        if(res.code == 200){
            console.log(res.data[type])
            let times = res.data[type];
            let isSuccess;
            isSuccess = new Date(times.startTime) < new Date() && new Date(times.endTime) > new Date() ? true : false;
            callback(isSuccess)
        }
    })
}
/*
  签字版
*/
// 调用签字版
export function pluginBar() {
    console.log('调用签字版')
    var message = {};
    message = {
        "messageType": 1,//	业务类型  0->初始化设备 1->调用签批
        "signid": "",//页面接收签字图片数据的img元素id名称
        "logo": "",//公司LOGO
        "penWidth": 2, //笔宽值自定义设置，取值范围：1-4，取值类型：整数
        "dialog": {
            /******************************
             X与Y不设置时，签名窗口弹出时，默认显示在屏幕正中间。
             ******************************/
            "X": 630,// 签名窗口弹出时显示在屏幕位置的X坐标值。
            "Y": 360,//签名窗口弹出时显示在屏幕位置的Y坐标值。
            "width": 550,//窗口宽度，添加窗口关闭按钮后，建议窗体最低宽度设置为550，界面显示美观正常。
            "height": 300,//窗口高度。
            "signBackColor": 14743776,//签字区域背景色，颜色值可以接受10进制和16进制数值，颜色数值顺序RGB。e0f8e0
            "dialogBackColor": 16448505,//签字窗口背景色，颜色值可以接受10进制和16进制数值，颜色数值顺序RGB。fafbf9
            //签字区域背景图，当与签字区域背景色冲突时，签字区域背景图优先级更高。
            "signBackImage": "base64data"//设置签字区域背景图，需要传入图片的BASE64数据。不用传递Data URI。

        },
        "image": {
            "imageType": 2,//生成签名图片的类型 1->BMP(图片数据支持2MB以下), 2->JPG, 3->PNG, 4->GIF
            "imageWidth": 330,//返回签字图片宽度。
            "imageHeight": 180//返回签字图片高度。
        }
    };

    var evt = document.createEvent("CustomEvent");
    evt.initCustomEvent('hanvon_signProEvent', true, false, message);
    document.dispatchEvent(evt);
}
